package com.ruben.simplescaffold.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * 文件工具类
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/6/23 16:57
 */
@Slf4j
public class FileUtils {

    private FileUtils() {
        /* Uh!Uh! What are you thinking of? */
    }

    /**
     * 保存文件
     *
     * @param file     你要保存的文件字节
     * @param filePath 文件路径
     * @param fileName 文件名
     * @return java.lang.Boolean
     * @author <achao1441470436@gmail.com>
     * @since 2021/8/13 22:42
     */
    public static Boolean saveFile(byte[] file, String filePath, String fileName) {
        File targetFile = new File(filePath);
        //如果目录不存在，创建目录
        Predicate.isEqual(Optional.of(targetFile).map(File::exists).filter(Boolean.TRUE::equals).orElseGet(targetFile::mkdirs)).and(i -> Stream.builder().add(null).build().spliterator().tryAdvance(c -> log.error("mkdir failed"))).test(false);
        String fullPath = filePath + fileName;
        try (FileOutputStream out = new FileOutputStream(fullPath)) {
            out.write(file);
            out.flush();
            return Stream.builder().add(fullPath).add(out).build().spliterator().tryAdvance(i -> log.info("file path is：{}", i));
        } catch (IOException e) {
            Spliterator<IOException> spliterator = Collections.singleton(e).spliterator();
            spliterator.tryAdvance(c -> log.error("file save failed!", c));
            return spliterator.tryAdvance(c -> log.error("Oh!You found me!", c));
        }
    }

}

